package com.hd.trans.utils

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.hd.trans.framework.rom.IOUtils
import com.hd.trans.ui.component.RecordFileCallback
import com.hd.trans.utils.thread.ThreadWrapper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

open class RecordFileCallbackImpl: RecordFileCallback {
    private var recordFiles: HashMap<String,File?> = hashMapOf()
    private var recordFileOS: FileOutputStream? = null
    var currentTaskId:String = ""
    //音频保存中
    private val _recordSaving = MutableLiveData<Boolean>()
    val recordSaving: LiveData<Boolean> = _recordSaving

    override fun createRecordFile(taskId: String) {
        try {
            recordFileOS?.close()
            val timeString = System.currentTimeMillis().toString()
            val recordFilePath = FileUtils.getPcmFileAbsolutePath("${timeString}_recording")
            val recordFile = File(recordFilePath)
            recordFileOS = FileOutputStream(recordFile) // 建立一个可存取字节的文件
            currentTaskId = taskId
            recordFiles[taskId] = recordFile
        } catch (e: Exception) {
            LogUtil.e("createRecordFile", e.toString())
        }
    }

    override fun writeByteToFile(bytes: ByteArray) {
        try {
            if (recordFileOS != null) {
                recordFileOS!!.write(bytes)
            }
        } catch (e: IOException) {
            LogUtil.e("writeByteToFile", e.toString())
        }
    }

    override fun savePcmToWav(taskId: String) {
    }

    fun saveAudioFile(taskId: String,block:(String)->Unit){
        val recordFile = popAudioFile(taskId)
        if (recordFile == null || !recordFile.exists()) {
            block.invoke("")
            return
        }
        _recordSaving.postValue(true)

        try {
            if (recordFileOS != null) {
                IOUtils.closeQuietly(recordFileOS) // 关闭写入流
                recordFileOS = null
                val wavPath = FileUtils.getWavFileAbsolutePath("tong_" + System.currentTimeMillis())
                GlobalScope.launch {
                    PcmToWav.makePCMFileToWAVFile(recordFile.absolutePath, wavPath, true)
                    recordFile.delete()
                    withContext(Dispatchers.Main){
                        //切换到Main线程（即UI线程）
                        block.invoke(wavPath)
                    }
                }
            }
        }catch (e:Exception){
            block.invoke("")
        }

        _recordSaving.postValue(false)
    }

    private fun popAudioFile(taskId: String?):File?{
        if (taskId == null)
            return null
        return recordFiles.remove(taskId)
    }

    fun release(){
        ThreadWrapper.ioThreadExecute {
            IOUtils.closeQuietly(recordFileOS)
            recordFiles.forEach{
                it.value?.delete()
            }
        }

    }
}
